package com.example.concurrent.demo.callable;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author susc
 * @title: CallableDemo
 * @projectName concurrent-demo
 * @description: TODO
 * @date 2021/9/2810:48
 */
public class CallableDemo {
    private static final int CORE_POOL_SIZE = 5;
    private static final int MAX_POOL_SIZE = 10;
    private static final int QUEUE_CAPACITY  = 100;
    private static final Long KEEP_ALIVE_TIME = 1L;

    public static void main(String[] args) {
        // 使用阿里巴巴推荐的创建线程池方式
        // 通过ThreadPoolExecutor构造函数自定义参数创建
        TimeUnit unit;
        BlockingQueue workQueue;
        ThreadPoolExecutor excutor = new ThreadPoolExecutor(
                CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(QUEUE_CAPACITY), new ThreadPoolExecutor.CallerRunsPolicy());

        List<Future<String>> futureList = new ArrayList<>();
        Callable<String> callable = new MyCallable();
        for(int i = 0; i < 10; i++){
            // 提交任务到线程池
            Future<String> future = excutor.submit(callable);
            // 将返回值future添加到list,我们可以通过future获得执行的Callable得到返回值
            futureList.add(future);
        }

        for (Future<String> fut: futureList){
            try {
                String threadInfo = new Date() + "::" + fut.get();
                System.out.println(threadInfo);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }

        // 关闭线程池
        excutor.shutdown();
    }
}
